package com.rpc.learn.transport.handler;

import com.rpc.learn.serialize.Serializer;
import com.rpc.learn.serialize.SerializerFactory;
import com.rpc.learn.transport.dto.RpcRequest;
import com.rpc.learn.transport.dto.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class CustomObjectEncoder extends MessageToByteEncoder {
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        byte msgType;
        if(msg instanceof RpcRequest) {
            msgType = (byte)1;
        }else if(msg instanceof RpcResponse){
            msgType = (byte)2;
        }else {
            throw new RuntimeException("不支持的数据类型");
        }
        Serializer serializer = SerializerFactory.getSerializer();
        byte[] bytes = serializer.serialize(msg);
        int dataLength = 0;
        if(bytes != null) {
            dataLength = bytes.length;
        }
        out.writeInt(dataLength + 4 + 1);   // 整个消息帧的长度： 实际数据 + 消息长度 + 消息类型
        out.writeByte(msgType); // 消息类型 请求 还是响应
        out.writeBytes(bytes);  // 实际数据
    }
}
